﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using BLL.Services.Categories;
using Web.Infrastructure.Models;

namespace Web.Areas.Admin.Models.Categories
{
    public class CategoriesEditModel : BaseModel, IValidatableObject
    {
        public CategoriesEditModel(Category category)
        {
            ToModel(category, this);
        }

        public CategoriesEditModel()
        {
        }

        [UIHint("hidden")]
        [Remote("Validate", "Categories", "Admin", AdditionalFields = "Name", ErrorMessage = "Category with the same name already exists.")]
        public int CategoryId { get; set; }
        
        [Required]
        [Display(Name = "Category Name")]
        [StringLength(256)]
        [Remote("Validate", "Categories", "Admin", AdditionalFields = "CategoryId", ErrorMessage = "Category with the same name already exists.")]
        public string Name { get; set; }

        public static explicit operator Category(CategoriesEditModel model)
        {
            var category = new Category();
            ToEntity(model, category);
            return category;
        }

        /// <summary>
        /// Gets the category service.
        /// </summary>
        /// <value>
        /// The category service.
        /// </value>
        protected static ICategoriesService CategoryService
        {
            get
            {
                return DependencyResolver.Current.GetService<ICategoriesService>();
            }
        }

        /// <summary>
        /// Determines whether the specified object is valid.
        /// </summary>
        /// <param name="validationContext">The validation context.</param>
        /// <returns>
        /// A collection that holds failed-validation information.
        /// </returns>
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>();
            if (!CategoryService.ValidateCategory(CategoryId, Name))
            {
                result.Add(new ValidationResult("Category with the same name already exists."));
            }
            return result;
        }
    }
}